package com.example.demo.controller;

import com.example.demo.entity.ResultEntity;
import com.example.demo.service.TokenService;
import com.example.demo.service.serviceimpl.UserServiceImpl;
import com.example.demo.tool.KoDoTool;
import com.example.demo.vo.UsersVo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RequestMapping("v2/users/")
@CrossOrigin
@RestController
public class UsersController {

    @Value("${project.localfilepath}")
    private String localfilepath;//文件上传本地临时路径
    @Resource
    KoDoTool koDoTool;//注入七牛云上传方法
    @Resource
    TokenService tokenService;
    @Resource
    UserServiceImpl userService;
    
    // 添加用户
    @PostMapping("addUser")
    private ResultEntity addUser(@RequestBody UsersVo usersVo) {
        ResultEntity resultEntity = new ResultEntity();
        try {
            if (userService.addUser(usersVo) > 0) {
                resultEntity.setCount("当前新增用户id"+usersVo.getId());
                resultEntity.setCode(0);
                resultEntity.setData(usersVo);
                resultEntity.setMsg("創建成功");
            } else {
                resultEntity.setCode(1);
                resultEntity.setMsg("創建失败");
            }
        } catch (Exception e) {
            resultEntity.setCode(-1);
            resultEntity.setMsg("数据获取失败");
            e.printStackTrace();
        }
        return resultEntity;
    }
    // 删除用户
    @DeleteMapping("deleteUser/{id}")
    private ResultEntity deleteUser(@PathVariable("id") int id){
        ResultEntity resultEntity = new ResultEntity();
        try {
            if(id==1){
                resultEntity.setCode(3);
                resultEntity.setMsg("管理员不允许删除");
            }
            else {
                if (userService.delUser(id) > 0) {
                    resultEntity.setCode(0);
                    resultEntity.setMsg("删除成功");
                } else {
                    resultEntity.setCode(1);
                    resultEntity.setMsg("删除失败");
                }
            }
        } catch (Exception e) {
            resultEntity.setCode(-1);
            resultEntity.setMsg("数据获取失败");
            e.printStackTrace();
        }
        return resultEntity;
    }
    // 用户登录
    @GetMapping("dologin")
    private ResultEntity doLogin(@RequestParam("username")String username,@RequestParam("password")String password){
        ResultEntity resultEntity=new ResultEntity();
        try{

            if(userService.doLogin(username,password)!=null){
                resultEntity.setCode(0);
                resultEntity.setMsg("登录成功");

                String token=tokenService.createToken(username);
                resultEntity.setData(token);
            }else{
                resultEntity.setCode(-1);
                resultEntity.setMsg("密码错误");
            }
        }catch (Exception e) {
            e.printStackTrace();
            resultEntity.setCode(-1);
            resultEntity.setMsg("系统错误");
        }
        return resultEntity;
    }
    // 用户登出
    @PostMapping("doexit")
    private  ResultEntity doExit(@RequestParam("username") String username){
        ResultEntity resultEntity=new ResultEntity();
        try{
            if(tokenService.clearToken(username)){
                resultEntity.setCode(0);
                resultEntity.setMsg("退出成功！");
            }else{
                resultEntity.setCode(1);
                resultEntity.setMsg("退出失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
            resultEntity.setCode(-1);
            resultEntity.setMsg("系统错误");
        }
        return resultEntity;
    }
    
    // 更新用户信息
    @PutMapping("updateUser")
    private ResultEntity updateUser(@RequestBody UsersVo usersVo) {
        ResultEntity resultEntity = new ResultEntity();
        try {
            if (userService.updateUser(usersVo) > 0) {
                resultEntity.setCode(0);
                resultEntity.setMsg("更新成功");
                resultEntity.setData(usersVo);
            } else {
                resultEntity.setCode(-1);
                resultEntity.setMsg("更新失败");
            }
        } catch (Exception e) {
            resultEntity.setCode(-1);
            resultEntity.setMsg("错误");
            e.printStackTrace();
        }
        return resultEntity;
    }
    
    // 根据用户名获取用户信息
    @GetMapping("getUserByUsername")
    private ResultEntity getUserByUsername(@RequestParam("username") String username) {
        ResultEntity resultEntity = new ResultEntity();
        try {
            resultEntity.setData(userService.getUserByUsername(username));
            resultEntity.setCode(0);
            resultEntity.setMsg("获取成功");
        } catch (Exception e) {
            resultEntity.setCode(-1);
            resultEntity.setMsg("获取用户信息失败");
            e.printStackTrace();
        }
        return resultEntity;
    }
    /**
     * 修改头像
     * @param avatar 头像文件
     * @param id 用户id
     * @return ResultEntity
     */
    @PostMapping("changehead")
    private ResultEntity changeHead(@RequestParam("avatar") MultipartFile avatar, @RequestParam("id") int id){
        ResultEntity resultEntity = new ResultEntity();
        try{
            String suffixName = avatar.getOriginalFilename().substring(avatar.getOriginalFilename().lastIndexOf("."));//获取文件后缀名
            String fileNewName= UUID.randomUUID().toString()+suffixName;//新的文件名
            String fileAndPath=localfilepath+fileNewName;//文件名+路径
            File file = new File(fileAndPath);//文件对象
            if(!file.getParentFile().exists()){//如果文件夹不存在
                file.mkdirs();//新建文件夹
            }
            try{
                avatar.transferTo(file);
                String headUrl= koDoTool.UploadFileToKoDo(fileAndPath);//上传到七牛云的头像地址
                if(userService.changeUHead(id,headUrl)>0){
                    resultEntity.setCode(0);
                    resultEntity.setMsg("头像修改成功!");
                }else{
                    resultEntity.setCode(1);
                    resultEntity.setMsg("头像修改失败!");
                }
            }catch (Exception e){
                e.printStackTrace();
                resultEntity.setCode(-2);
                resultEntity.setMsg("文件上传本地服务器失败");
            }
        }catch (Exception e){
            resultEntity.setCode(-1);
            resultEntity.setMsg("数据获取失败！");
            e.printStackTrace();
        }
        return resultEntity;
    }
}
